package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisLock implements ILOCK{

    //业务名称
    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public RedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //key的前缀
    private static final String KEY="lock:";
    //uuid前缀
    private static final String uuid= UUID.randomUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> LOCK;
    static {
        LOCK=new DefaultRedisScript<>();
        LOCK.setLocation(new ClassPathResource("lock.lua"));
        LOCK.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程id
        String id = uuid+Thread.currentThread().getId();
        Boolean set = stringRedisTemplate.opsForValue().setIfAbsent(KEY+name, id, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(set);
    }

    @Override
    public void unlock() {
        //使用lua脚本使redis具有事务性
        stringRedisTemplate.execute(LOCK, Collections.singletonList(KEY+name),uuid+Thread.currentThread().getId());
    }
//    @Override
//    public void unlock() {
//        //获取线程
//        String id = uuid+Thread.currentThread().getId();
//        //获取redisid
//        String s = stringRedisTemplate.opsForValue().get(KEY + name);
//        if (s.equals(id)){
//            stringRedisTemplate.delete(KEY+name);
//        }
//    }
}
